//
//  ViewController.m
//  SoundRecond
//
//  Created by qie on 16/4/7.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

#define kAudioFileName @"test.caf"

@interface ViewController () <AVAudioRecorderDelegate>

@property (nonatomic, strong) UIButton *btn;

@property (nonatomic,strong) AVAudioRecorder *audioRecorder; //音频录音机
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;     //音频播放器
@property (nonatomic,strong) NSTimer *timer;            //录音监控

@property (weak, nonatomic) IBOutlet UIProgressView *audioPower;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setAudioSessionAndRecoder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/**
 *  设置音频会话
 */
-(void)setAudioSessionAndRecoder {
    // 获得录音机对象
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url = [self getSavePath];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled = YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
        }
    }
    if ([self.audioRecorder prepareToRecord]) {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        //设置为播放和录音状态，以便可以在录制完之后播放录音
        NSError *error;
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
        if (error) {
            NSLog(@"setCategory error = %@",error);
        }
        [audioSession setActive:YES error:&error];
        if (error) {
            NSLog(@"setActive error = %@",error);
        }
    }
}

/**
 *  录音文件设置
 *
 *  @return 返回录音设置
 */
- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    return dicM;
}

/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
-(NSURL *)getSavePath {
    NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr = [urlStr stringByAppendingPathComponent:kAudioFileName];
    NSLog(@"file path:%@",urlStr);
    NSURL *url = [NSURL fileURLWithPath:urlStr];
    return url;
}

/**
 *  创建播放器
 *
 *  @return 播放器
 */
-(AVAudioPlayer *)getAudioPlayer {
    if (!_audioPlayer) {
//        NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"caf"];
//        NSURL *url = [NSURL fileURLWithPath:urlStr];
        NSURL *url = [self getSavePath];
        NSError *error = nil;
        _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        _audioPlayer.numberOfLoops = 0;
        [_audioPlayer prepareToPlay];
        if (error) {
            NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)audioPowerChange {
    [self.audioRecorder updateMeters];  //更新测量值
    float power = [self.audioRecorder averagePowerForChannel:0]; //取得第一个通道的音频，注意音频强度范围时-160到0
    NSLog(@"强度 %f",power);
    self.audioPower.progress = (1.0 / 160) * (power + 160);
}

#pragma mark - AVAudioRecorderDelegate

//录音成功
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    NSString *str = flag ? @"成功" : @"失败";
    NSLog(@"录音结束%@",str);
    if (![_audioPlayer isPlaying]) {
        [_audioPlayer play];
    }
}
//录音失败
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    NSLog(@"录音失败%@",[error localizedDescription]);
}

#pragma mark - IBActions

/**
 *  点击录音按钮
 *
 *  @param sender 录音按钮
 */
- (IBAction)startRecord:(id)sender {
    if (![_audioRecorder isRecording]) {
        BOOL flag = [_audioRecorder record];
        if (flag) {
            NSLog(@"开启成功");
        }
        self.timer.fireDate = [NSDate distantPast];
    }
}

/**
 *  点击取消录音按钮
 *
 *  @param sender 取消录音按钮
 */
- (IBAction)cancelRecord:(id)sender {
    _audioRecorder.delegate = nil;
    if ([_audioRecorder isRecording]) {
        [_audioRecorder stop];
    }
    _audioRecorder = nil;
}

/**
 *  点击暂定按钮
 *
 *  @param sender 暂停按钮
 */
- (IBAction)pause:(id)sender {
    if ([_audioRecorder isRecording]) {
        [_audioRecorder pause];
        self.timer.fireDate = [NSDate distantFuture];
    }
}

/**
 *  点击恢复按钮
 *  恢复录音只需要再次调用record，AVAudioSession会帮助你记录上次录音位置并追加录音
 *
 *  @param sender 恢复按钮
 */
- (IBAction)goon:(id)sender {
    [self startRecord:nil];
}

/**
 *  点击停止按钮
 *
 *  @param sender 停止按钮
 */
- (IBAction)stop:(id)sender {
    if ([_audioRecorder isRecording]) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        // 此处需要恢复设置回放标志，否则会导致其它播放声音也会变小
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [session setActive:YES error:nil];
        
        [_audioRecorder stop];
        self.timer.fireDate = [NSDate distantFuture];
    }
}

/**
 *  点击播放按钮
 *
 *  @param sender 播放按钮
 */
- (IBAction)play:(id)sender {
    if (_audioPlayer == nil) {
        [self getAudioPlayer];
    }
    
    
    if (![_audioPlayer isPlaying]) {
        [_audioPlayer play];
    }
}

@end
